// 引入高德地图SDK（需从高德开放平台下载）
import AMapWX from '@/ya/helper/amap-wx.js'

class MapService {
  constructor() {
    this.amapPlugin = null
    this.initStatus = false
  }

  /**
   * 初始化地图服务
   * @param {string} key - 高德地图开发者Key
   */
  init(key) {
    if (!this.initStatus) {
      this.amapPlugin = new AMapWX.AMapWX({
        key: key,
        // 坐标系配置（关键参数）
        coordType: 'gcj02',  // 采用国测局坐标系[2,7](@ref)
        sdkVersion: '2.0'
      })
      this.initStatus = true
    }
  }

  /**
   * 获取当前位置（含权限管理）
   * @returns {Promise} 包含经纬度的Promise对象
   */
  async getCurrentLocation() {
    return new Promise((resolve, reject) => {
      // 先检查定位权限[4,7](@ref)
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.userLocation']) {
            this.requestLocationAuth().then(() => {
              this._getLocation(resolve, reject)
            }).catch(reject)
          } else {
            this._getLocation(resolve, reject)
          }
        }
      })
    })
  }

  /**
   * 逆地址解析（坐标转中文地址）
   * @param {number} longitude - 经度
   * @param {number} latitude - 纬度
   * @returns {Promise} 包含地址信息的Promise对象
   */
  reverseGeocode(longitude, latitude) {
    return new Promise((resolve, reject) => {
      this.amapPlugin.getRegeo({
        location: `${longitude},${latitude}`,
        success: data => {
          const address = {
            formatted: data[0].name + data[0].desc, // 完整地址[8](@ref)
            province: data[0].regeocodeData.addressComponent.province,
            city: data[0].regeocodeData.addressComponent.city
          }
          resolve(address)
        },
        fail: err => reject(err)
      })
    })
  }

  /**
   * 路线规划（支持驾车/步行/公交）
   * @param {Object} params 
   * @param {string} params.origin - 起点坐标 
   * @param {string} params.destination - 终点坐标
   * @param {string} [params.mode=driving] - 交通方式
   * @returns {Promise} 路线数据Promise
   */
  async routePlan(params) {
    const modes = {
      driving: 'getDrivingRoute',
      walking: 'getWalkingRoute',
      transit: 'getTransitRoute'
    }
    const method = modes[params.mode] || 'getDrivingRoute'

    return new Promise((resolve, reject) => {
      this.amapPlugin[method]({
        origin: params.origin,
        destination: params.destination,
        city: params.city || '', // 公交规划必填[6](@ref)
        success: res => {
          const result = this._parseRouteData(res)
          resolve(result)
        },
        fail: reject
      })
    })
  }

  // 私有方法：实际获取位置
  _getLocation(resolve, reject) {
    wx.getLocation({
      type: 'gcj02', // 强制使用高德坐标系[2,7](@ref)
      isHighAccuracy: true, // 开启高精度模式[7](@ref)
      success: resolve,
      fail: reject
    })
  }

  // 私有方法：请求定位授权
  async requestLocationAuth() {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: '位置授权提示',
        content: '需要获取您的位置以提供导航服务',
        success: res => {
          if (res.confirm) {
            wx.openSetting({
              success: settingRes => {
                if (settingRes.authSetting['scope.userLocation']) resolve()
                else reject(new Error('用户未授权'))
              }
            })
          } else {
            reject(new Error('用户拒绝授权'))
          }
        }
      })
    })
  }

  // 私有方法：解析路线数据
  _parseRouteData(data) {
    return {
      distance: data.distance + '米',
      duration: data.time + '分钟',
      polyline: data.path.map(p => ({
        points: p.split(';').map(point => {
          const [longitude, latitude] = point.split(',')
          return { longitude: parseFloat(longitude), latitude: parseFloat(latitude) }
        })
      })),
      steps: data.steps || []
    }
  }
}

export default new MapService()